<script setup name="BizUserInfoIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import { listBizCompany } from "@/api/biz/bizCompany";
import { parseTime } from "@/utils/aidex";
import {
  listBizUserInfo,
  delBizUserInfo,
  exportBizUserInfo,
  updateBizUserInfo
} from "@/api/biz/bizUserInfo";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();

const data = ref({
  loading: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  // 搜索
  search: {
    nikeName: "",
    phone: "",
    user: "",
    isShiming: ""
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  form: { companyId: "" },
  userInfo: {},
  listCompany: [],
  isShimingList: [
    { value: "0", label: "未实名" },
    { value: "1", label: "已实名" }
  ],
  type: ""
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  getListCompany();
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});
// 获取公司
function getListCompany() {
  listBizCompany({ pageSize: 50 }).then((res) => {
    data.value.listCompany = res.data.list;
  });
}
// 重置
function clear() {
  data.value.search.nikeName = "";
  data.value.search.name = "";
  data.value.search.phone = "";
  data.value.search.isShiming = "";
  data.value.search.orderByColumn = "";
  data.value.search.isAsc = "";
  getDataList();
}
// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
// function sortChange(prop, order) {
//   onSortChange(prop, order).then(() => getDataList());
// }
// 查询
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.nikeName && (params.nikeName = data.value.search.nikeName);
  data.value.search.name && (params.name = data.value.search.name);
  data.value.search.phone && (params.phone = data.value.search.phone);
  data.value.search.isShiming &&
    (params.isShiming = data.value.search.isShiming);
  data.value.search.orderByColumn &&
    (params.sort = data.value.search.orderByColumn);
  data.value.search.isAsc && (params.order = data.value.search.isAsc);
  listBizUserInfo(params).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.data.list;
    pagination.value.total = res.data.total;
  });
}

// 编辑
function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.visible = true;
  }
}
//查看会员详情
function onDetails(id) {
  console.log("查看详情", id);
}
// 添加
function onshowAccount(row) {
  // data.value.formModeProps.id = "";
  // data.value.formMode = "dialog";
  // data.value.formModeProps.visible = true;

  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });

  if (ids.length > 0) {
    if (ids.length == 1) {
    } else {
      ElMessage.warning({ message: "请选择一个用户", center: true });
    }
  } else {
    ElMessage.warning({ message: "请选择用户", center: true });
  }
}
// 批量删除 单独删除
function onDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.name ||
    data.value.batch.selectionDataList.map((item) => {
      return item.name;
    });
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delBizUserInfo(ids).then((res) => {
          getDataList();
          if (res.code == 200)
            ElMessage.success({
              message: "删除成功",
              center: true
            });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择用户", center: true });
  }
}
function handleCommand(command) {
  if (command.option == "edit") {
    onEdit(command.item);
  }
  if (command.option == "setInfo") {
  }
}

const dialogFormVisible = ref(false);

// open  设置回收员窗口
function openSetting(row, type) {
  dialogFormVisible.value = true;
  data.value.userInfo = row;
  data.value.type = type;
}
// 确定设置
function settingHuishou() {
  dialogFormVisible.value = false;
  data.value.userInfo.companyId = data.value.form.companyId;
  confirmEvent(data.value.userInfo, data.value.type);
}

/**
 * 处理排序
 * @param {*} column
 */
function sortChange(column) {
  if (column.column != null) {
    console.log(column);
    data.value.search.orderByColumn = column.prop;
    if (column.order == "ascending") {
      data.value.search.isAsc = "asc";
    } else if (column.order == "descending") {
      data.value.search.isAsc = "desc";
    }
  }
  getDataList();
}
const confirmEvent = (row, type) => {
  row.type = type;
  updateBizUserInfo(row).then((res) => {
    ElMessage.success({
      message: "操作成功",
      center: true
    });
    getDataList();
  });
};
const confirmEventIsShiming = (row) => {
  row.isShiming = "0";
  updateBizUserInfo(row).then((res) => {
    ElMessage.success({
      message: "操作成功",
      center: true
    });
    getDataList();
  });
};
const cancelEvent = () => {
  console.log("cancel!");
};
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="5">
              <el-form-item label="用户昵称">
                <el-input
                  v-model="data.search.nikeName"
                  placeholder="用户昵称"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="真实姓名">
                <el-input
                  v-model="data.search.name"
                  placeholder="真实姓名"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="电话">
                <el-input
                  v-model="data.search.phone"
                  placeholder="电话"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="是否实名">
                <el-select v-model="data.search.isShiming">
                  <el-option
                    v-for="(item, index) in data.isShimingList"
                    :value="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-button type="primary" @click="currentChange()">
                <template #icon>
                  <el-icon>
                    <svg-icon name="ep:search" />
                  </el-icon>
                </template>
                查询
              </el-button>
              <el-button @click="clear()">
                <template #icon>
                  <el-icon>
                    <svg-icon name="ant-design:reload-outlined" />
                  </el-icon>
                </template>
                重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>

      <div style="height: calc(100vh - 350px); overflow-y: auto">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          @sort-change="sortChange"
          @selection-change="data.batch.selectionDataList = $event"
        >
          >
          <el-table-column type="selection" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80"
          />
          <el-table-column
            prop="avatar"
            label="头像"
            show-overflow-tooltip
            width="80"
            align="center"
          >
            <template v-slot="scope">
              <el-avatar :src="scope.row.avatar"></el-avatar>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="name" label="真实姓名" show-overflow-tooltip>
            <template v-slot="scope">
              <el-link type="primary" @click="onEdit(scope.row)">{{
                scope.row.name
              }}</el-link>
            </template>
          </el-table-column> -->
          <el-table-column prop="nikeName" label="用户名" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="phone" label="电话" show-overflow-tooltip>
            <template v-slot="scope">
              <el-link type="primary">{{ scope.row.phone }}</el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="isShiming"
            label="是否实名"
            show-overflow-tooltip
            width="100"
            align="center"
          >
            <template v-slot="scope">
              <el-tag type="info" v-if="scope.row.isShiming == 0"
                >未实名</el-tag
              >
              <el-tag type="success" v-else>已实名</el-tag>
            </template>
          </el-table-column>

          <!-- <el-table-column
            prop="account"
            label="余额"
            show-overflow-tooltip
            align="right"
            sortable="custom"
          >
            <template v-slot="scope">
              ¥ &nbsp;{{
                scope.row.account ? scope.row.account.toFixed(2) : 0.0
              }}
            </template>
          </el-table-column> -->
          <el-table-column
            prop="energycount"
            label="积分"
            show-overflow-tooltip
            align="right"
            sortable="custom"
          >
            <template v-slot="scope">
              &nbsp;{{
                scope.row.energycount ? scope.row.energycount.toFixed(2) : 0.0
              }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="tuijianUser"
            label="推荐人"
            show-overflow-tooltip
          ></el-table-column> -->
          <el-table-column
            prop="type"
            label="用户类型"
            show-overflow-tooltip
            width="100"
            align="center"
          >
            <template v-slot="scope">
              <el-tag type="success" v-if="scope.row.type == 0"
                >普通用户</el-tag
              >
              <el-tag type="warning" v-else>回收员</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="createTime"
            label="创建时间"
            show-overflow-tooltip
            width="140"
            align="center"
            ><template v-slot="scope">
              {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</template
            >
          </el-table-column>
          <el-table-column label="操作" width="230" align="left">
            <template #default="scope">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确定设置该用户为回收员？"
                @confirm="openSetting(scope.row, '1')"
                @cancel="cancelEvent"
                v-if="scope.row.type == '0'"
              >
                <template #reference>
                  <el-button type="primary" size="small" text>
                    <template #icon>
                      <el-icon>
                        <svg-icon name="ep:setting" />
                      </el-icon>
                    </template>
                    设置回收员</el-button
                  >
                </template>
              </el-popconfirm>

              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确定取消该回收员？"
                @confirm="confirmEvent(scope.row, '0')"
                @cancel="cancelEvent"
                v-if="scope.row.type == '1'"
              >
                <template #reference>
                  <el-button type="danger" size="small" text>
                    <template #icon>
                      <el-icon>
                        <svg-icon name="ep:close-bold" />
                      </el-icon>
                    </template>
                    取消回收员</el-button
                  >
                </template>
              </el-popconfirm>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确定取消用户实名？"
                @confirm="confirmEventIsShiming(scope.row)"
                @cancel="cancelEvent"
                v-if="scope.row.isShiming == '1'"
              >
                <template #reference>
                  <el-button type="warning" size="small" text>
                    <template #icon>
                      <el-icon>
                        <svg-icon name="ep:close-bold" />
                      </el-icon>
                    </template>
                    取消实名</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog
        v-model="dialogFormVisible"
        title="设置上门取件员驿站信息"
        width="440px"
      >
        <el-form :model="form">
          <el-form-item label="选择所属驿站" label-width="auto">
            <el-select v-model="data.form.companyId" style="width: 100%">
              <el-option
                :value="item.id"
                :label="item.companyName"
                v-for="(item, index) in data.listCompany"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="settingHuishou()">
              确定设置
            </el-button>
          </span>
        </template>
      </el-dialog>
      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
  </div>
</template>

<style scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  display: flex;
  align-items: center;
  margin-top: 3px;
}
</style>
